package com.lyy.system.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lyy.system.pojo.SysImgCode;
import com.lyy.system.service.SysImgCodeService;
import org.springframework.web.bind.annotation.*;
import com.lyy.common.utils.ResultInfo;
import com.lyy.common.utils.ResultUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang3.StringUtils;
import com.lyy.common.utils.jxls.JxlsExport;
import com.lyy.common.utils.jxls.JxlsUtils;
import com.lyy.common.utils.*;

import java.io.InputStream;

import org.springframework.web.multipart.MultipartFile;
import com.lyy.common.utils.excel.ExcelUtils;
import com.lyy.common.utils.AssertUtils;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.HashMap;
import java.util.ArrayList;
import java.util.Date;
import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.math.BigDecimal;

/**
 * 图形验证码(SysImgCode)表控制层
 *
 * @author Yw
 * @since 2021-02-05 13:55:26
 */
@RestController
@RequestMapping("/sysImgCode")
public class SysImgCodeController {
    /**
     * 服务对象
     */
    @Resource
    private SysImgCodeService sysImgCodeService;

    /**
     * 创建图形验证码
     * /sysImgCode/createSysImgCode
     * { "vcode":"动态验证码",  "createDate":"创建时间" }
     *
     * @param vcode      动态验证码
     * @param createDate 创建时间
     * @return
     */
    @PostMapping("/createSysImgCode")
    public Map<String, Object> createSysImgCode(SysImgCode sysImgCode) {
        AssertUtils.notNull(sysImgCode.getVcode(), "动态验证码不能为空");
        AssertUtils.notNull(sysImgCode.getCreateDate(), "创建时间不能为空");
        sysImgCodeService.createSysImgCode(sysImgCode);
        return ResultUtils.getResult(ResultInfo.SUCCESS);
    }

    /**
     * 根据主键修改图形验证码
     * /sysImgCode/updateSysImgCode
     * { "id":"验证码id",  "vcode":"动态验证码",  "createDate":"创建时间" }
     *
     * @param id         验证码id
     * @param vcode      动态验证码
     * @param createDate 创建时间
     * @return
     */
    @PutMapping("/updateSysImgCode")
    public Map<String, Object> updateSysImgCode(SysImgCode sysImgCode) {
        AssertUtils.notNull(sysImgCode.getId(), "验证码id不能为空");
        AssertUtils.notNull(sysImgCode.getVcode(), "动态验证码不能为空");
        AssertUtils.notNull(sysImgCode.getCreateDate(), "创建时间不能为空");
        sysImgCodeService.updateSysImgCode(sysImgCode);
        return ResultUtils.getResult(ResultInfo.SUCCESS);
    }

    /**
     * 根据主键获取单个图形验证码
     * /sysImgCode/getSysImgCode
     * { "id":"验证码id" }
     *
     * @param id 验证码id
     * @return
     */
    @GetMapping("/getSysImgCode")
    public Map<String, Object> getSysImgCode(SysImgCode sysImgCode) {
        AssertUtils.notNull(sysImgCode.getId(), "验证码id不能为空");
        SysImgCode entity = sysImgCodeService.getSysImgCode(sysImgCode);
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("sysImgCode", entity);
        return ResultUtils.getResult(ResultInfo.SUCCESS, "", map);
    }


    /**
     * 根据主键删除图形验证码
     * /sysImgCode/deleteSysImgCode
     * { "id":"验证码id" }
     *
     * @param id 验证码id
     * @return
     */
    @DeleteMapping("/deleteSysImgCode")
    public Map<String, Object> deleteSysImgCode(SysImgCode sysImgCode) {
        AssertUtils.notNull(sysImgCode.getId(), "验证码id不能为空");
        sysImgCodeService.deleteSysImgCode(sysImgCode);
        return ResultUtils.getResult(ResultInfo.SUCCESS);
    }

    /**
     * 查询图形验证码列表
     * /sysImgCode/selectSysImgCodeList
     * { "id":"验证码id",  "vcode":"动态验证码",  "createDate":"创建时间" }
     *
     * @param id         验证码id
     * @param vcode      动态验证码
     * @param createDate 创建时间
     * @return
     */
    @GetMapping("/selectSysImgCodeList")
    public Map<String, Object> selectSysImgCodeList(SysImgCode sysImgCode) {
        List<SysImgCode> sysImgCodes = sysImgCodeService.selectSysImgCodeList(sysImgCode);
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("sysImgCodes", sysImgCodes);
        return ResultUtils.getResult(ResultInfo.SUCCESS, "", map);
    }

    /**
     * 查询图形验证码列表
     * /sysImgCode/selectSysImgCodeCount
     * { "id":"验证码id", "vcode":"动态验证码", "createDate":"创建时间"}
     *
     * @param id         验证码id
     * @param vcode      动态验证码
     * @param createDate 创建时间
     * @return
     */
    @GetMapping("/selectSysImgCodeCount")
    public Map<String, Object> selectSysImgCodeCount(SysImgCode sysImgCode) {
        int count = sysImgCodeService.selectSysImgCodeCount(sysImgCode);
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("count", count);
        return ResultUtils.getResult(ResultInfo.SUCCESS, "", map);
    }


    /**
     * 查询图形验证码列表分页
     * /sysImgCode/selectSysImgCodePage
     * { "id":"验证码id",  "vcode":"动态验证码",  "createDate":"创建时间" ,"pageNum":"页码","pageSize":"条数"}
     *
     * @param pageNum    页码
     * @param pageSize   页数
     * @param id         验证码id
     * @param vcode      动态验证码
     * @param createDate 创建时间
     * @return
     */
    @GetMapping("/selectSysImgCodePage")
    public Map<String, Object> selectSysImgCodePage(SysImgCode sysImgCode, Integer pageNum, Integer pageSize) {
        AssertUtils.notNull(pageNum, "页码不能为空!");
        AssertUtils.notNull(pageSize, "条数不能为空!");
        PageHelper.startPage(pageNum, pageSize);
        List<SysImgCode> sysImgCodes = sysImgCodeService.selectSysImgCodeList(sysImgCode);
        PageInfo<SysImgCode> pageInfo = new PageInfo<>(sysImgCodes);
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("pageInfo", pageInfo);
        return ResultUtils.getResult(ResultInfo.SUCCESS, "", map);
    }


    /**
     * 导出图形验证码
     * /sysImgCode/exportSysImgCodeExcel
     * { "id":"验证码id",  "vcode":"动态验证码",  "createDate":"创建时间" }
     *
     * @param id         验证码id
     * @param vcode      动态验证码
     * @param createDate 创建时间
     * @return
     */
    @GetMapping("/exportSysImgCodeExcel")
    public void exportSysImgCodeExcel(HttpServletRequest request, HttpServletResponse response, SysImgCode sysImgCode) {
        List<SysImgCode> sysImgCodes = sysImgCodeService.selectSysImgCodeList(sysImgCode);
        if (CommonUtils.isNotEmpty(sysImgCodes)) {
            List<String> titles = new ArrayList<>();
            titles.add(" 序号 ");
            titles.add(" 动态验证码 ");
            titles.add(" 创建时间 ");
            List<List<String>> values = new ArrayList<>();
            int k = 0;
            for (SysImgCode entity : sysImgCodes) {
                List<String> value = new ArrayList<>();
                value.add((++k) + "");
                value.add(entity.getVcode());
                value.add(DateUtils.formatDate(entity.getCreateDate()));
                values.add(value);
            }
            String address = Constants.address + "/wisdom/template/customTemplate.xls";
            String excelName = "图形验证码.xls";
            Map<String, Object> beans = new HashMap<>();
            beans.put("titles", titles);
            beans.put("values", values);
            beans.put("date", DateUtils.formatDateTime(new Date()));
            JxlsExport.export(request, response, beans, excelName, address);
        }
    }


    /**
     * /sysImgCode/importSysImgCodeExcel  从excel表导入图形验证码
     * 导入excel文件
     * {"file":"excel文件"}
     *
     * @param file excel文件
     */
    @PostMapping("/importSysImgCodeExcel")
    public Map<String, Object> importSysImgCodeExcel(MultipartFile file) {
        if (file.isEmpty()) {
            return ResultUtils.getResult(ResultInfo.UPLOAD_NOT_EXISTS);
        }
        // 文件名称
        String fileName = file.getOriginalFilename();
        if (StringUtils.isBlank(fileName)) {
            return ResultUtils.getResult(ResultInfo.UPLOAD_NOT_EXISTS);
        }
        try {
            InputStream inputStream = file.getInputStream();
            //创建工作簿
            Workbook wb = null;
            //判断表格格式
            if (fileName.toLowerCase().endsWith("xls")) {
                wb = new HSSFWorkbook(inputStream);
            } else if (fileName.toLowerCase().endsWith("xlsx")) {
                wb = new XSSFWorkbook(inputStream);
            } else {
                return ResultUtils.getResult(ResultInfo.UPLOAD_TYPE_ERROR);
            }
            List<SysImgCode> sysImgCodes = new ArrayList<>();
            List<Map<String, String>> resultMap = new ArrayList<>();
            Map<String, String> result = null;
            SysImgCode sysImgCode = null;
            // 获取工作表的第一个Sheet
            Sheet hssfSheet = wb.getSheetAt(0);
            if (hssfSheet != null) {
                int index = -1;
                for (int rowNum = 0; rowNum <= hssfSheet.getLastRowNum(); rowNum++) {
                    Row hssfRow = hssfSheet.getRow(rowNum);
                    if (hssfRow != null) {
                        if (ExcelUtils.getValue(hssfRow.getCell(0)).contains("动态验证码") &&
                                ExcelUtils.getValue(hssfRow.getCell(1)).contains("创建时间")) {
                            index = ++rowNum;
                            break;
                        }
                    }
                }

                if (index == -1) {
                    result = new HashMap<>();
                    result.put("reason", "excel模板不正确");
                    result.put("status", "1");
                    resultMap.add(result);
                    Map<String, Object> map = new HashMap<>();
                    map.put("resultMap", resultMap);
                    return ResultUtils.getResult(ResultInfo.SUCCESS, "", map);
                }

                // 循环行Row
                for (int rowNum = index; rowNum <= hssfSheet.getLastRowNum(); rowNum++) {
                    Row hssfRow = hssfSheet.getRow(rowNum);
                    if (hssfRow != null) {
                        if (StringUtils.isBlank(ExcelUtils.getValue(hssfRow.getCell(0))) &&
                                StringUtils.isBlank(ExcelUtils.getValue(hssfRow.getCell(1)))) {
                            continue;
                        }
                        sysImgCode = new SysImgCode();
                        String vcode = ExcelUtils.getValue(hssfRow.getCell(0));//动态验证码
                        if (StringUtils.isBlank(vcode)) {
                            result = new HashMap<>();
                            result.put("reason", "动态验证码不能为空！");
                            result.put("status", "1");
                            resultMap.add(result);
                            continue;
                        }
                        sysImgCode.setVcode(vcode);
                        String createDate = ExcelUtils.getValue(hssfRow.getCell(1));//创建时间
                        if (StringUtils.isBlank(createDate)) {
                            result = new HashMap<>();
                            result.put("reason", "创建时间不能为空！");
                            result.put("status", "1");
                            resultMap.add(result);
                            continue;
                        }
                        sysImgCode.setCreateDate(DateUtils.formatDate(createDate));
                        sysImgCodes.add(sysImgCode);
                    }
                }
                if (CommonUtils.isNotEmpty(sysImgCodes)) {
                    resultMap.addAll(sysImgCodeService.importSysImgCodeExcel(sysImgCodes));
                }
            }
            inputStream.close();
            Map<String, Object> map = new HashMap<>();
            map.put("resultMap", resultMap);
            return ResultUtils.getResult(ResultInfo.SUCCESS, "", map);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
            return ResultUtils.getResult(ResultInfo.ERROR);
        }
        return ResultUtils.getResult(ResultInfo.FAILED);
    }
}
